﻿using Dapper;
using ERPEF.Model;
using ERPIService;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SalesOrderController : ControllerBase
    {
        private readonly sal_SalesOrderService sal_SalesOrder;
        private readonly sal_SalesOrder_cService sal_SalesOrder_CService;

        private readonly MyDbContext myDbContext;
        public SalesOrderController(MyDbContext myDb, sal_SalesOrderService sal_SalesOrderService, sal_SalesOrder_cService sal_SalesOrder_CService)
        {
            myDbContext = myDb;
            sal_SalesOrder = sal_SalesOrderService;
            this.sal_SalesOrder_CService = sal_SalesOrder_CService;
        }

        /// <summary>
        /// 主表分页查询
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        public ActionResult<FenYe<sal_sales_orders>> getFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "so_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "sal_sales_orders"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数


                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<sal_sales_orders>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<sal_sales_orders> fenYe = new FenYe<sal_sales_orders>()
                {
                    SaleOrderData = result,
                    Rows = row,
                };

                if (fenYe.SaleOrderData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        /// <summary>
        ///从表分页查询
        /// </summary>
        /// <returns></returns> 
        /// 
        [HttpGet]
        public ActionResult<FenYe<sal_orders>> ModelFromFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "orders_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "sal_orders"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<sal_orders>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<sal_orders> fenYe = new FenYe<sal_orders>()
                {
                    SaleOrder_cData = result,
                    Rows = row,
                };

                if (fenYe.SaleOrder_cData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //销售订单主表添加
        [HttpPost]
        public async Task<IActionResult> AddSaleZB([FromBody] sal_sales_orders sal_Sales_Orders)
        {
            // 查询当前最大编码
            int maxCodeNumber = int.Parse(await GetMaxCodeNumber());

            // 生成新编码
            string newCode = GenerateSaleCode(maxCodeNumber);

            sal_Sales_Orders.so_code = newCode;

            if (ModelState.IsValid)
            {
                int result = await sal_SalesOrder.Add(sal_Sales_Orders);
                if (result > 0)
                {
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        private async Task<string> GetMaxCodeNumber()
        {
            // 从数据库中获取最大的仓库编码数字部分
            string maxCodeString = await myDbContext.sal_sales_orders
                .Where(w => w.so_code.StartsWith("XSDD"))
                .Select(w => w.so_code.Substring(12))
                .OrderByDescending(code => code)
                .FirstOrDefaultAsync<string?>();

            // 如果数据库中没有记录或者记录的编码不符合预期格式，则返回 "0001"
            if (string.IsNullOrEmpty(maxCodeString))
            {
                return "01";
            }
            // 解析最大编码的数字部分
            int maxCodeNumber = int.Parse(maxCodeString);
            Console.WriteLine(maxCodeNumber);

            // 生成新的编码数字部分
            int newCodeNumber = maxCodeNumber + 1;

            // 如果新的编码数字部分超过了99，则重置为01
            if (newCodeNumber > 99)
            {
                newCodeNumber = 1;
            }
            return newCodeNumber.ToString();

        }
        // 生成新的仓库编码
        private string GenerateSaleCode(int codeNumber)
        {
            // 获取当前日期的字符串表示形式，格式为 "yyyyMMdd"
            string dateString = DateTime.Now.ToString("yyyyMMdd");

            // 将数字转换为两位字符串，并在前面补零
            string codeString = codeNumber.ToString("D2");

            // 返回完整的编码，包括前缀 "XSDD"、日期部分和数字部分
            return "XSDD" + dateString + codeString;
        }
        //销售订单从表添加
        [HttpPost]
        public async Task<IActionResult> AddSaleCB(sal_orders sal_Orders)
        {
            if (ModelState.IsValid)
            {
                int result = await sal_SalesOrder_CService.Add(sal_Orders);
                if (result > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        /// <summary>
        /// 修改主表
        /// </summary>
        /// <returns></returns> 
        [HttpPut]
        public async Task<IActionResult> UpdateClient(sal_sales_orders sal_Sales_Orders)
        {

            if (ModelState.IsValid)
            {
                sal_Sales_Orders.sal_Orders = null;
                int result = await sal_SalesOrder.Update(sal_Sales_Orders);

                // 首先检查审核状态
                if (sal_Sales_Orders.AuditStatus)
                {
                    return BadRequest("修改失败：该订单已被审核，不能进行修改！");
                }
                // 检查退货状态，如果为 "1" 或 "2"，则不允许修改
                if (sal_Sales_Orders.so_Return_status == "1" || sal_Sales_Orders.so_Return_status == "2")
                {
                    return BadRequest("修改失败：该订单已提交退货申请，不能进行修改！");
                }
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        /// <summary>
        /// 从表修改
        /// </summary>
        /// <returns></returns> 
        [HttpPut]
        public async Task<IActionResult> FormUpdateClient(sal_orders sal_Orders)
        {
            if (ModelState.IsValid)
            {
                int result = await sal_SalesOrder_CService.UpdateModel(sal_Orders);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }
        /// <summary>
        /// 删除主表
        /// </summary>
        /// <returns></returns> 
        [HttpDelete("{so_id}")]
        public async Task<string> FromDelete(int so_id)
        {
            var sal = await myDbContext.sal_sales_orders
                .Include(m => m.sal_Orders)
                .SingleOrDefaultAsync(m => m.so_id == so_id);
            if (sal == null || sal.IsDeleted == true)
            {
                return "未找到对应的数据";
            }
            var undeletedFroms = sal.sal_Orders.Any(f => f.IsDeleted == false);

            if (undeletedFroms)
            {
                return "存在关联数据，删除失败";
            }
            sal.IsDeleted = true;
            await myDbContext.SaveChangesAsync();

            return "删除成功";
        }

        /// <summary>
        /// 从表删除
        /// </summary>
        /// <returns></returns> 
        [HttpDelete("{orders_id}")]
        public async Task<IActionResult> FromDeleteModel(int orders_id)
        {
            int result = await sal_SalesOrder_CService.Delete(orders_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }
       
        /// <summary>
        /// 销售订单审核
        /// </summary>
        /// <param name="so_id"></param>
        /// <returns></returns>
        [HttpPost("{so_id}")]
        public async Task<IActionResult> AuditSalesOrder(int so_id)
        {
            // 从数据库中获取销售订单及其关联的订单详情
            var salesOrder = await myDbContext.sal_sales_orders
                .Include(so => so.sal_Orders) // 确保加载关联的订单详情
                .FirstOrDefaultAsync(so => so.so_id == so_id);

            
            // 如果销售订单不存在或已经被逻辑删除，则返回错误信息
            if (salesOrder == null || salesOrder.IsDeleted)
            {
                return NotFound("未找到对应的数据");
            }
            // 检查从表sal_Orders是否有数据
            if (!salesOrder.sal_Orders.Any() || salesOrder.sal_Orders.All(order => order.IsDeleted))
            {
                return BadRequest("从表没有数据，不能进行审核");
            }
            // 检查退货状态，如果为1或2，则不能进行审核
            if ( salesOrder.so_Return_status == "2")
            {
                return BadRequest("该订单已经进行退货，不能进行审核");
            }
            try
            {
                // 审核销售订单
                salesOrder.AuditStatus = true;
                salesOrder.so_status = '1';
                salesOrder.auditor = "Admin";
                salesOrder.auditTime = DateTime.UtcNow;

                // 创建一个新的销售出库单对象
                var salesOut = new sal_sales_Out
                {
                    out_id = 0, // 让数据库自动生成
                    out_code = salesOrder.so_code, // 销售单号等于出库单号
                    client_head = salesOrder.client_head,
                    so_c_property = salesOrder.so_c_property,
                    so_packaging = salesOrder.so_packaging,
                    client_name = salesOrder.client_name,
                    client_phone = salesOrder.client_phone,
                    out_sales_date = DateTime.UtcNow,
                    so_shipment_status = salesOrder.so_shipment_status,
                    so_status = '1',
                    employee_name = salesOrder.employee_name,
                    IsDeleted = salesOrder.IsDeleted,
                    so_created_by = salesOrder.so_created_by,
                    so_created_time = DateTime.UtcNow,
                    so_update_by = salesOrder.so_update_by,
                    so_update_time = DateTime.UtcNow, // 使用当前时间作为更新时间

                    out_Return_status=salesOrder.so_Return_status


                    //so_toNum = salesOrder.so_toNum   //销售数量  新增字段
                };
                // 将新的销售出库单添加到数据库
                myDbContext.sal_sales_Out.Add(salesOut);
                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                int newOutId = salesOut.out_id; // 获取自增的out_id

                // 遍历销售订单从表信息，为每条记录创建销售出库从表对象
                foreach (var order in salesOrder.sal_Orders)
                {
                    var salesOutC = new sal_sales_Out_C
                    {
                        inventory_quantity =0,
                        orders_product_name = order.orders_product_name,
                        order_quantity = order.orders_num, 
                        outbound_quantity = order.orders_num, 
                        IsDeleted = false,
                        sal_sales_Outout_id = newOutId,
                        w_Name = ""
                    };
                    myDbContext.sal_sales_Out_C.Add(salesOutC);
                }
                // 保存从表信息
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，并且已创建对应的销售出库单");
            }
            catch (DbUpdateException ex)
            {
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }

        
    }
}
